package com.ruoyi.system.controller;

import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import com.github.pagehelper.util.StringUtil;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.font.FontProvider;
import com.lowagie.text.DocumentException;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.system.util.TextFooterEventHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TbDiagnosisInfo;
import com.ruoyi.system.service.ITbDiagnosisInfoService;
import com.ruoyi.common.core.controller.BaseController;
import javax.imageio.ImageIO;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.layout.Document;


/**
 * 诊断信息Controller
 *
 * @author ruoyi
 * @date 2024-05-09
 */
@Api("诊断信息")
@Controller
@RequestMapping("/system/INFO")
public class TbDiagnosisInfoController extends BaseController
{
    private String prefixUser = "Judge";

    @Autowired
    private ITbDiagnosisInfoService tbDiagnosisInfoService;


    /**
     * 新增保存诊断信息
     */
    @ApiOperation("新增保存诊断信息")
    @Log(title = "诊断信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public String addSave(@RequestBody TbDiagnosisInfo tbDiagnosisInfo) throws IOException, DocumentException {

        Date now2 = new Date();
        SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMddHHmmsss");
        tbDiagnosisInfo.setUserID(prefixUser+format1.format(now2));
        Integer row = tbDiagnosisInfoService.insertTbDiagnosisInfo(tbDiagnosisInfo);
        TbDiagnosisInfo tbDiagnosisInfo1 = null;
        if(row == 1){
            //查询数据
            tbDiagnosisInfo1 = tbDiagnosisInfoService.selectTbDiagnosisInfoByUserID(prefixUser+format1.format(now2));
            //读取pdf流
//            File templateFile = new File("E:\\demo.html");
            //从下载路径获取
            File templateFile = new File(RuoYiConfig.getDownloadPath()+"template.html");

            //读取文件
            String content = null;
            try {
                content = FileUtils.readFileToString(templateFile, "utf-8");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            //修改内容   \\$content\\$为上面页面$$符号和里面的内容。
            DefaultCategoryDataset datasetLine = new DefaultCategoryDataset();
            String[] arr = tbDiagnosisInfo1.getPulseDataAd().split(",");
            for (int i = 0; i < arr.length; i++) {
                Float data = Float.parseFloat(arr[i]);
                datasetLine.addValue(data, "pules", String.valueOf(i));
            }
            for (String str :arr){
                Float data = Float.parseFloat(str);
                datasetLine.addValue( data , "" , "" );
            }
            JFreeChart chart = ChartFactory.createLineChart(
                    "",
                    "",
                    "",
                    datasetLine,
                    PlotOrientation.VERTICAL,
                    true, true, false);
//            ChartUtilities.saveChartAsPNG(new File("E:\\LineChart+"+tbDiagnosisInfo1.getUserID()+"_pules.png"), chart, 600, 200);
//            String pulesBase64 = "data:image/png;base64,"+convertImageToBase64Str("E:\\LineChart+"+tbDiagnosisInfo1.getUserID()+"_pules.png");
            ChartUtilities.saveChartAsPNG(new File(RuoYiConfig.getUploadPath()+tbDiagnosisInfo1.getUserID()+"_pules.png"), chart, 600, 200);
            String pulesBase64 = "data:image/png;base64,"+convertImageToBase64Str(RuoYiConfig.getUploadPath()+tbDiagnosisInfo1.getUserID()+"_pules.png");
            DefaultCategoryDataset datasetBar = new DefaultCategoryDataset();
            datasetBar.addValue(Integer.parseInt(tbDiagnosisInfo1.getBloodHigh()), "收缩压", "收缩压");
            datasetBar.addValue(Integer.parseInt(tbDiagnosisInfo1.getBloodLow()), "舒张压", "舒张压");

            JFreeChart chartBar = ChartFactory.createBarChart3D(
                    "",
                    "血压",
                    "number",
                    datasetBar,
                    PlotOrientation.VERTICAL,
                    false, true, false);
//            ChartUtilities.saveChartAsPNG(new File("E:\\LineChart+"+tbDiagnosisInfo1.getUserID()+"_blood.png"), chartBar, 300, 150);
//            String bloodBase64 = "data:image/png;base64,"+convertImageToBase64Str("E:\\LineChart+"+tbDiagnosisInfo1.getUserID()+"_blood.png");
            ChartUtilities.saveChartAsPNG(new File(RuoYiConfig.getUploadPath()+tbDiagnosisInfo1.getUserID()+"_blood.png"), chartBar, 300, 150);
            String bloodBase64 = "data:image/png;base64,"+convertImageToBase64Str(RuoYiConfig.getUploadPath()+tbDiagnosisInfo1.getUserID()+"_blood.png");

            content = content.replaceAll("\\{constitutionTrait}", StringUtil.isEmpty(tbDiagnosisInfo1.getConstitutionTrait())?"未知":tbDiagnosisInfo1.getConstitutionTrait());
            content = content.replaceAll("\\{pulesBase64}", StringUtil.isEmpty(pulesBase64)?"":pulesBase64);
            content = content.replaceAll("\\{bloodBase64}", StringUtil.isEmpty(bloodBase64)?"":bloodBase64);
            content = content.replaceAll("\\{bloodHigh}",StringUtil.isEmpty(tbDiagnosisInfo1.getBloodHigh())?"未知":tbDiagnosisInfo1.getBloodHigh());
            content = content.replaceAll("\\{bloodLow}",StringUtil.isEmpty(tbDiagnosisInfo1.getBloodLow())?"未知":tbDiagnosisInfo1.getBloodLow());
            content = content.replaceAll("\\{formationReason}",StringUtil.isEmpty(tbDiagnosisInfo1.getFormationReason())?"无":tbDiagnosisInfo1.getFormationReason());
            content = content.replaceAll("\\{formationSymptom}",StringUtil.isEmpty(tbDiagnosisInfo1.getFormationSymptom())?"无":tbDiagnosisInfo1.getFormationSymptom());
            content = content.replaceAll("\\{adviceEat}",StringUtil.isEmpty(tbDiagnosisInfo1.getAdviceEat())?"无":tbDiagnosisInfo1.getAdviceEat());
            content = content.replaceAll("\\{adviceSport}",StringUtil.isEmpty(tbDiagnosisInfo1.getAdviceSport())?"无":tbDiagnosisInfo1.getAdviceSport());
            content = content.replaceAll("\\{advicePsychology}",StringUtil.isEmpty(tbDiagnosisInfo1.getAdvicePsychology())?"无":tbDiagnosisInfo1.getAdvicePsychology());
            content = content.replaceAll("\\{remark1}",StringUtil.isEmpty(tbDiagnosisInfo1.getRemark1())?"":tbDiagnosisInfo1.getRemark1());
            content = content.replaceAll("\\{remark2}",StringUtil.isEmpty(tbDiagnosisInfo1.getRemark2())?"":tbDiagnosisInfo1.getRemark2());
            content = content.replaceAll("\\{remark3}",StringUtil.isEmpty(tbDiagnosisInfo1.getRemark3())?"":tbDiagnosisInfo1.getRemark3());
            // 写入
//            File File = new File("E:\\demo_01.html");
            File File = new File(RuoYiConfig.getDownloadPath()+tbDiagnosisInfo1.getUserID()+"中医体质分析报告.html");
            OutputStream fos = null;
            try {
                fos = new FileOutputStream(File);
                fos.write(content.getBytes("UTF-8"));
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
            //关流
            fos.flush();
            fos.close();

            try {
//                String pdfPath = "E:\\"+tbDiagnosisInfo1.getUserID()+"中医体质分析报告.pdf";
//
                String pdfPath = RuoYiConfig.getDownloadPath()+tbDiagnosisInfo1.getUserID()+"中医体质分析报告.pdf";
                PdfWriter pdfWriter = new PdfWriter(new File(pdfPath));
                PdfDocument pdfDocument = new PdfDocument(pdfWriter) ;
                Document doc = new Document(pdfDocument);
                pdfDocument.setDefaultPageSize(PageSize.A4);
                pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, new TextFooterEventHandler(doc));
                ConverterProperties pro =  new ConverterProperties();
                FontProvider fontProvider = new DefaultFontProvider();
                fontProvider.addSystemFonts();
                pro.setFontProvider(fontProvider);
//                HtmlConverter.convertToPdf(new FileInputStream("E:\\demo_01.html"), pdfDocument, pro);
                HtmlConverter.convertToPdf(new FileInputStream(RuoYiConfig.getDownloadPath()+tbDiagnosisInfo1.getUserID()+"中医体质分析报告.html"), pdfDocument, pro);

                //更新地址
                TbDiagnosisInfo tbDiagnosisInfo2 = new TbDiagnosisInfo();
                tbDiagnosisInfo2.setUserID(tbDiagnosisInfo1.getUserID());
                tbDiagnosisInfo2.setQrCodeUrl(tbDiagnosisInfo1.getUserID()+"中医体质分析报告.pdf");
                tbDiagnosisInfoService.updateTbDiagnosisInfo(tbDiagnosisInfo2);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //存储地址生成二维码
            //返回二维码
        }
        return tbDiagnosisInfo1.getUserID();
    }

    /**
     * 图片转Base64字符串
     * @param imageFileName
     * @return
     */
    public static String convertImageToBase64Str(String imageFileName) {
        ByteArrayOutputStream baos = null;
        try {
            //获取图片类型
            String suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
            //构建文件
            File imageFile = new File(imageFileName);
            //通过ImageIO把文件读取成BufferedImage对象
            BufferedImage bufferedImage = ImageIO.read(imageFile);
            //构建字节数组输出流
            baos = new ByteArrayOutputStream();
            //写入流
            ImageIO.write(bufferedImage, suffix, baos);
            //通过字节数组流获取字节数组
            byte[] bytes = baos.toByteArray();
            //获取JDK8里的编码器Base64.Encoder转为base64字符
            return Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
